package com.smart.system.controller;

import cn.hutool.core.date.DateTime;
import com.smart.aop.log.LogType;
import com.smart.aop.log.SaveLog;
import com.smart.aop.permission.HasPermission;
import com.smart.common.utils.DateUtil;
import com.smart.entity.system.JwznBusinessDataEntity;
import com.smart.model.excel.annotation.ExcelField;
import com.smart.model.response.r.Result;
import com.smart.model.response.r.ResultCode;
import com.smart.model.response.r.ResultWrapper;
import com.smart.service.system.JwznBusinessDataService;
import com.smart.tools.excel.ExcelExport;
import com.smart.tools.excel.ExcelImport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * final Controller
 *
 * @author wf
 * @since 2025-04-30 11:30:33
 */
@RestController
@RequestMapping("/system/jwznBusinessData")
public class JwznBusinessDataController {
    @Autowired
    JwznBusinessDataService jwznBusinessDataService;
    @Autowired
    ResultWrapper resultWrapper;

    /**
     * 列表
     *
     * @param jwznBusinessDataEntity finalbean
     * @return String
     */
    @GetMapping("/page")
    public String page(JwznBusinessDataEntity jwznBusinessDataEntity) {
        return Result.data(jwznBusinessDataService.findPage(jwznBusinessDataEntity));
    }

    /**
     * 列表（不分页）
     *
     * @param jwznBusinessDataEntity finalbean
     * @return String
     */
    @GetMapping("/list")
    public String list(JwznBusinessDataEntity jwznBusinessDataEntity) {
        return Result.data(jwznBusinessDataService.findList(jwznBusinessDataEntity));
    }

    /**
     * 信息
     *
     * @param id 主键ID
     * @return String
     */
    @GetMapping("/get")
    public String get(@RequestParam String id) {
        JwznBusinessDataEntity result = jwznBusinessDataService.get(id);
        return result != null ? Result.data(result) : Result.fail(ResultCode.FAIL);
    }

    /**
     * 保存
     *
     * @param jwznBusinessDataEntity finalbean
     * @return String
     */
    @HasPermission("jwznBusinessData:add")
    @PostMapping("/save")
    @SaveLog(module = "final管理" , type = LogType.ADD)
    public String save(@RequestBody JwznBusinessDataEntity jwznBusinessDataEntity) {
        JwznBusinessDataEntity result = jwznBusinessDataService.saveEntity(jwznBusinessDataEntity);
        return result != null ? Result.data(result) : Result.fail(ResultCode.FAIL);
    }

    /**
     * 修改
     *
     * @param jwznBusinessDataEntity finalbean
     * @return String
     */
    @HasPermission("jwznBusinessData:update")
    @PostMapping("/update")
    @SaveLog(module = "final管理" , type = LogType.UPDATE)
    public String update(@RequestBody JwznBusinessDataEntity jwznBusinessDataEntity) {
        JwznBusinessDataEntity result = jwznBusinessDataService.updateEntity(jwznBusinessDataEntity);
        return result != null ? Result.data(result) : Result.fail(ResultCode.FAIL);
    }

    /**
     * 删除
     *
     * @param jwznBusinessDataEntity finalbean
     * @return String
     */
    @HasPermission("jwznBusinessData:delete")
    @PostMapping("/delete")
    @SaveLog(module = "final管理" , type = LogType.DELETE)
    public String delete(@RequestBody JwznBusinessDataEntity jwznBusinessDataEntity) {
        return Result.status(jwznBusinessDataService.delete(jwznBusinessDataEntity));
    }

    @GetMapping("/pieChart")
    public String pieChart(){
        return Result.data(jwznBusinessDataService.getNameCountMap());
    }
//    /**
//     * 根据点位名称和当天日期获取耗电量
//     * @param name 点位名称
//     * @param date 日期
//     * @return 耗电量
//     */
//    @GetMapping("/barchart")
//    public String getHourlyPowerConsumption(
//            @RequestParam String name,
//            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date date) {
//        if (date == null) {
//            date = new Date();
//        }
//        Calendar calendar = Calendar.getInstance();
//        calendar.setTime(date);
//        calendar.set(Calendar.HOUR_OF_DAY, 0);
//        calendar.set(Calendar.MINUTE, 0);
//        calendar.set(Calendar.SECOND, 0);
//        calendar.set(Calendar.MILLISECOND, 0);
//
//        List<Map<String, Object>> result = new ArrayList<>();
//        for (int i = 0; i < 12; i++) {
//            Date start = calendar.getTime();
//            int startHour = calendar.get(Calendar.HOUR_OF_DAY); // 使用 Calendar 获取小时数（替代 Date.getHours()）
//            calendar.add(Calendar.HOUR_OF_DAY, 2);
//            Date end = calendar.getTime();
//            int endHour = calendar.get(Calendar.HOUR_OF_DAY); // 使用 Calendar 获取小时数（替代 Date.getHours()）
//
//            Double consumption = jwznBusinessDataService.getConsumptionByNameAndTimeRange(name, start, end);
//            Map<String, Object> item = new HashMap<>();
//            item.put("time", String.format("%02d:00 - %02d:00", startHour, endHour)); // 使用 Calendar 获取的小时数
//            item.put("consumption", consumption);
//            result.add(item);
//        }
//
//        return Result.data(result);
//    }
@GetMapping("/barChart")
public String barChart(@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") DateTime startTime,
                       @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") DateTime endTime){
    //给定picktime(两个),查询出name和对应的consume
    return Result.data(jwznBusinessDataService.getNameConsumeMap(startTime, endTime));
}




    /**
     * 导出
     *
     * @param jwznBusinessDataEntity finalbean
     * @param response 响应
     */
    @HasPermission("jwznBusinessData:export")
    @PostMapping(value = "/export")
    public void exportData(@RequestBody JwznBusinessDataEntity jwznBusinessDataEntity, HttpServletResponse response) {
        List<JwznBusinessDataEntity> list = resultWrapper.setListIdentityInfo(jwznBusinessDataService.findList(jwznBusinessDataEntity), JwznBusinessDataEntity.class);
        String fileName = "final数据" + DateUtil.getDate("yyyyMMddHHmmss") + ".xlsx";
        try (ExcelExport export = new ExcelExport("final数据", JwznBusinessDataEntity.class)) {
            export.setDataList(list).write(response, fileName);
        }
    }

    /**
     * 导入
     *
     * @param request 请求
     */
    @HasPermission("jwznBusinessData:import")
    @PostMapping(value = "/import")
    public String importData(MultipartHttpServletRequest request) {
        MultiValueMap<String, MultipartFile> multiFileMap = request.getMultiFileMap();
        List<MultipartFile> files = multiFileMap.get("files");
        try (ExcelImport excelImport = new ExcelImport(files.get(0), 2, 0)) {
            List<JwznBusinessDataEntity> dataList = excelImport.getDataList(JwznBusinessDataEntity.class);
            return Result.status(jwznBusinessDataService.saveBatch(dataList));
        } catch (Exception e) {
            return Result.fail("导入失败！");
        }
    }

    /**
     * 下载导入模板
     *
     * @param response 响应
     */
    @GetMapping(value = "/downloadTemplate")
    public void downloadTemplate(HttpServletResponse response) {
        String fileName = "导入final模板.xlsx";
        try (ExcelExport export = new ExcelExport("final数据", JwznBusinessDataEntity.class, null, ExcelField.Type.IMPORT)) {
            export.write(response, fileName);
        }
    }



    /**
     * 获取一天的折线图数据
     * @param name 电表名称
     * @param date 日期
     * @return 折线图数据
     */
    @GetMapping("/dailyLineChart")
    public String dailyLineChart(@RequestParam String name, @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") Date date) {
        return Result.data(jwznBusinessDataService.getDailyLineChartData(name, date));
    }

    /**
     * 获取一周的折线图数据
     * @param name 电表名称
     * @param startDate 开始日期
     * @return 折线图数据
     */
    @GetMapping("/weeklyLineChart")
    public String weeklyLineChart(@RequestParam String name, @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") Date startDate) {
        return Result.data(jwznBusinessDataService.getWeeklyLineChartData(name, startDate));
    }

    /**
     * 获取一月的折线图数据
     * @param name 电表名称
     * @param startDate 开始日期
     * @return 折线图数据
     */
    @GetMapping("/monthlyLineChart")
    public String monthlyLineChart(@RequestParam String name, @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") Date startDate) {
        return Result.data(jwznBusinessDataService.getMonthlyLineChartData(name, startDate));
    }
}
